import iconv from 'iconv-lite'

// 实现 addslashes 函数
export const addslashes = (str) => {
  return str.replace(/[\\"']/g, '\\$&');
}

// 实现 stripslashes 函数
export const stripslashes = (str) => {
  return str.replace(/\\(?![\s\S]*\\)/g, '');
}

// htmlspecialchars函数
export const htmlspecialchars = (str) => {
  // 定义一个对象，用于存储htmlspecialchars的替换规则
  const htmlspecialcharsMap = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  };
  return str.replace(/[&<>"']/g, function(match) {
    return htmlspecialcharsMap[match];
  });
}

// htmldecodespecialchars函数
export const htmldecodespecialchars = (str) => {
  // 定义一个对象，用于存储htmldecodespecialchars的替换规则
  const htmldecodespecialcharsMap = {
    '&amp;': '&',
    '&lt;': '<',
    '&gt;': '>',
    '&quot;': '"',
    '&#039;': "'"
  };
  return str.replace(/&amp;|&lt;|&gt;|&quot;|&#039;/g, function(match) {
    return htmldecodespecialcharsMap[match];
  });
}

// function utf8ToGbk(utf8Bytes) {
//   const decoder = new TextDecoder('gbk');
//   const gbkString = decoder.decode(new Uint8Array(utf8Bytes));
//   return new TextEncoder().encode(gbkString);
// }

// export const urlEncodeGbk = (str) => {
//   const gbkBytes = utf8ToGbk(new TextEncoder().encode(str));
//   return Array.from(gbkBytes).map(byte => `%${byte.toString(16).padStart(2, '0')}`).join('');
// }

// export const urlDecodeGbk = (str) => {
//   const bytes = [];
//   str.replace(/%([0-9A-Fa-f]{2})/g, (match, p1) => {
//     bytes.push(parseInt(p1, 16));
//   });
//   const decoder = new TextDecoder('gbk');
//   return decoder.decode(new Uint8Array(bytes));
// }

export const urlEncodeGbk = (str) => {
  const gbkBuffer = iconv.encode(str, 'gbk');
  return Array.from(gbkBuffer).map(byte => `%${byte.toString(16).padStart(2, '0')}`).join('');
}

export const urlDecodeGbk = (str) => {
  const bytes = [];
  str.replace(/%([0-9A-Fa-f]{2})/g, (match, p1) => {
    bytes.push(parseInt(p1, 16));
  });
  const gbkBuffer = Buffer.from(bytes);
  return iconv.decode(gbkBuffer, 'gbk');
}